<?php

namespace App\Listeners;

use App\Events\LevelEvent;
use App\Events\MedalEvent;
use App\Models\Member\CurrencyLog;
use App\Models\Member\Level;
use App\Models\Member\LevelNumberLog;
use App\Models\Member\Member;
use App\Models\Task\Finish;
use App\Models\Task\Task;
use App\Services\Member\CurrencyService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class LevelListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  LevelEvent  $event
     * @return void
     */
    public function handle(LevelEvent $event)
    {
        $member = Member::where('uuid', $event->member_uuid)->with('level')->first();
        $before_level_number = $member->level_number;

        $finishs = Finish::where('state', 1)->with('task')->where('member_uuid', $member->uuid)
            ->whereHas('task', function($query)use($member){
                $query->where('level', '<=', $member->level->level);
            })
            ->where('is_grant', 0)->get();

        foreach ($finishs as $finish){
            try {
                DB::beginTransaction();
                //当需要发放成长值时调用
                if(Task::levelNumberBySourceType()[$finish->task->id]['level_number'] > 0){
                    //1更新用户成长值
                    $after_level_number = bcadd($member->level_number, Task::levelNumberBySourceType()[$finish->task->id]['level_number'], 0);
                    $member->update([
                        'level_number' => $after_level_number,
                    ]);

                    event(new MedalEvent(1, $member->uuid));
                    event(new MedalEvent(2, $member->uuid));
                    event(new MedalEvent(3, $member->uuid));

                    //当用户等级升级之后更新用户等级
                    $level = Level::where('number','>=', $member->level_number)->orderBy('number', 'asc')->first();
                    if($level && $level->level > $member->level->level){
                        $member->update([
                            'level_uuid' => $level->uuid
                        ]);

                        $cacheLevels = Cache::get("level_".$member->uuid);
                        $cacheLevels[] = $level;

                        Cache::forever("level_".$member->uuid, $cacheLevels);

                        //更新用户等级之后通知等级解锁监听器
                        event(new LevelEvent($member->uuid));
                    }

                    //2增加成长值日志
                    LevelNumberLog::create([
                        'member_uuid' => $member->uuid,
                        'content' => Task::levelNumberBySourceType()[$finish->task->id]['content'],
                        'before_level_number' => $before_level_number,
                        'after_level_number' => $after_level_number,
                        'level_number' => Task::levelNumberBySourceType()[$finish->task->id]['level_number'],
                        'type' => 1,
                        'month' => date('Y-m-01'),
                        'source_type' => Task::levelNumberBySourceType()[$finish->task->id]['source_type'],
                    ]);

                    //3更新奖励发放状态
                    $finish->update([
                        'is_grant' => 1,
                    ]);

                    $cacheTasks = Cache::get("task_".$member->uuid);
                    $cacheTasks[] = Task::levelNumberBySourceType()[$finish->task->id];

                    Cache::put("task_".$member->uuid, $cacheTasks, 60);
                }

                //当需要发放积分时调用
                if(Task::levelNumberBySourceType()[$finish->task->id]['currency'] > 0){

                    CurrencyService::income($member->uuid, Task::levelNumberBySourceType()[$finish->task->id]['currency']
                        , Task::levelNumberBySourceType()[$finish->task->id]['source_type'], Task::levelNumberBySourceType()[$finish->task->id]['content']);
//                    //1.添加积分
//                    $after_currency = bcadd($member->currency, Task::levelNumberBySourceType()[$finish->task->id]['currency'], 0);
//
//                    $before_currency = $member->currency;
//                    $member->update([
//                        'currency' => $after_currency,
//                        'total_currency' => bcadd($member->total_currency, Task::levelNumberBySourceType()[$finish->task->id]['currency'], 0),
//                    ]);
//
//                    //2.增加积分日志
//                    CurrencyLog::create([
//                        'member_uuid' => $member->uuid,
//                        'content' => Task::levelNumberBySourceType()[$finish->task->id]['content'],
//                        'before_currency' => $before_currency,
//                        'after_currency' => $after_currency,
//                        'currency' => Task::levelNumberBySourceType()[$finish->task->id]['currency'],
//                        'type' => 1,
//                        'month' => date('Y-m-01'),
//                        'source_type' => Task::levelNumberBySourceType()[$finish->task->id]['source_type'],
//                    ]);

                    $cacheTasks = Cache::get("task_".$member->uuid);
                    $cacheTasks[] = Task::levelNumberBySourceType()[$finish->task->id];

                    Cache::put("task_".$member->uuid, $cacheTasks, 60);
                }
                
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
            }

        }



    }
}
